﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DoubleH.Utility;
using System.Collections;
using System.Windows.Controls.DataVisualization.Charting;
using System.Reflection;
using Table=FCNS.Data.Table;
using DoubleH.Utility.Configuration;

namespace ReportS.UC
{
    public struct CharProperty
    {
        public DataPointSeries Series { get; set; }
        public string ValueName { get; set; }//纵列绑定的数据库列名
        public string ValueTitle { get; set; }//标题
    }
    /// <summary>
    /// UCdataGrid.xaml 的交互逻辑
    /// </summary>
    public partial class UCdataGrid : UserControl
    {
        public UCdataGrid()
        {
            InitializeComponent();

            InitVar();
        }

        IEnumerable items = null;
        CharProperty[] Series = null;
        bool sum = true;
        UserUIparams userParams;
        //double startY = 0;

        object otherObjectForPrint = null;
        /// <summary>
        /// 设置打印中还需要的其它参数
        /// 例如打印列表的时候可能需要添加日期段
        /// 必须为类模式
        /// </summary>
        public object OtherObjectForPrint
        {
            set { otherObjectForPrint = value; }
        }

        bool absQuantity = true;
        /// <summary>
        /// 控件显示是否必须为正数
        /// </summary>
        public bool AbsQuantity
        {
            set { absQuantity = value; }
        }

        bool hideChart = true;
        /// <summary>
        /// 强制隐藏图表
        /// </summary>
        public bool HideChart
        {
            set {// hideChart = value;
            }
        }

        private void InitVar()
        {
            dataGridExt1.CanUserAddRows = false;
        }

        private void InitEvent()
        {
            //buttonPrint.Click += (ss, ee) => DoubleH.Utility.Print.PrintForm.ShowPrint(dataGridExt1, otherObjectForPrint,
            //    new MenuItemBinding() { TableText = userParams.TableText }, "报表\\" + userParams.TableText.ToString() + ".html");

            dataGridExt1.Sorting += (ss, ee) => InitData();
            buttonDownlad.Click += (ss, ee) => ExportFile();
            //gridTop.SizeChanged += (ss, ee) => userParams.ChartSplitLineHeight = ee.NewSize.Height;
        }

        private void ExportFile()
        {
            DoubleH.Utility.IO.FileTools ft = new DoubleH.Utility.IO.FileTools();
            ft.ExportDataGridToFile(dataGridExt1 , null);
        }

        public void Init(DataTableText tableText, IEnumerable ItemsSource, params CharProperty[] series)
        {
            Init(tableText, ItemsSource, false, series);
        }

        public void Init(DataTableText tableText, IEnumerable ItemsSource, bool sum, params CharProperty[] series)
        {
            if (userParams == null)
            {
                InitEvent();

                userParams = DoubleHConfig.UserConfig.GetUserUIparams(tableText);
                this.sum = sum;
                dataGridExt1.Init(userParams);
                if (string.IsNullOrEmpty(userParams.SortName))
                    userParams.SortName = ((Binding)((DataGridBoundColumn)dataGridExt1.Columns[0]).Binding).Path.Path;

                this.Series = series;
            }
            items = ItemsSource;
            if (items is IList)
                NormalUtility.SortColumn((IList)items, userParams.SortName, userParams.SortDirection);

            if (absQuantity)

                InitUI();
            InitData();
            Sum();
        }

        private void InitUI()
        {
            //gridTop.Height = userParams.ChartSplitLineHeight;
        }

        private void InitData()
        {
            dataGridExt1.ItemsSource = items;
            InitDataChart();
        }

        private void InitDataChart()
        {
            //if (Series.Length == 0 || items == null)
            //    return;

            //chart1.Series.Clear();
            //foreach (CharProperty cp in Series)
            //{
            //    List<KeyValuePair<string, double>> valueList = new List<KeyValuePair<string, double>>();
            //    Type type = items.AsQueryable().ElementType;
            //    PropertyInfo pKey = type.GetProperty(userParams.SortName);
            //    PropertyInfo pValue = type.GetProperty(cp.ValueName);

            //    if (pKey == null || pValue == null)
            //        continue;

            //    foreach (var item in items)
            //    {
            //        object kyObj = pKey.GetValue(item, null);
            //        if (kyObj == null)
            //            continue;

            //        string ky = userParams.SortName.Contains("DateTime") ? ((DateTime)kyObj).ToString("yyyy-MM-dd") : kyObj.ToString();
            //        object obj = pValue.GetValue(item, null);
            //        double kv = obj == null ? 0 : (double)obj;
            //        KeyValuePair<string, double>? kvp = valueList.Find(f => f.Key == ky);
            //        if (kvp == null)
            //            valueList.Add(new KeyValuePair<string, double>(ky, kv));
            //        else
            //        {
            //            kv = kv + kvp.Value.Value;
            //            valueList.Remove(kvp.Value);
            //            valueList.Add(new KeyValuePair<string, double>(ky, kv));
            //        }
            //    }

            //    cp.Series.DependentValuePath = "Value";
            //    cp.Series.IndependentValuePath = "Key";
            //    cp.Series.Title = cp.ValueTitle;
            //    cp.Series.ItemsSource = valueList;
            //    chart1.Series.Add(cp.Series);
            //}
        }
        /// <summary>
        /// 在标题显示统计数
        /// </summary>
        private void Sum()
        {
            if (!dataGridExt1.HasItems || !sum)
                return;

            PropertyInfo[] pi = dataGridExt1.Items[0].GetType().GetProperties();
            foreach (PropertyInfo info in pi)
            {
                if (!info.CanRead)
                    continue;
                string name = info.PropertyType.Name;
                if (name != "Int64" && name != "Int32" && name != "Double" && !name.Contains("Nullable"))
                    continue;

                foreach (DataGridTextColumn column in dataGridExt1.Columns)
                {
                    if (((Binding)column.Binding).Path.Path == info.Name)
                    {
                        string header = column.Header.ToString();
                        if (header.Contains("："))
                            header = header.Split('：')[0].Trim();
                        double dou = 0;

                        foreach (object obj in items)
                        {
                            object ob = info.GetValue(obj, null);
                            if (ob != null)
                                dou += Convert.ToDouble(ob);
                        }

                        column.Header = header + "\r\n：" + Math.Round(dou, Table.SysConfig.SysConfigParams.DecimalPlaces) + "";
                        break;
                    }
                }
            }
        }
    }
}